# -*- coding: utf-8 -*-

from django.core.paginator import Paginator as DjangoPaginator
from rest_framework.pagination import PageNumberPagination
from Apps.common.response import SuccessResponse

import math
import logging

logger = logging.getLogger('django')

"""
自定义分页格式及请求参数名
http://127.0.0.1:8000/systemUser/?page=1&pagesize=10
"""


class CustomPagination(PageNumberPagination):
    # page_size
    page_size = 10
    page_size_query_param = "page_size"  # 一页数量，重新定义key值
    max_page_size = 999
    django_paginator_class = DjangoPaginator

    return_page = 0

    def get_paginated_response(self, data):

        code = 200
        msg = 'success'
        res = {
            "page": int(self.return_page),
            "total": self.page.paginator.count,
            "pagesize": int(self.get_page_size(self.request)) or 10,
            "data": data
        }
        if not data:
            code = 200
            msg = "暂无数据"
            res['data'] = []

        return SuccessResponse(status=code, data=res, message=msg)

    def get_page_number(self, request, Paginator):
        page_number = request.query_params.get(self.page_query_param, 1)
        if page_number in self.last_page_strings:
            page_number = Paginator.num_pages

        #######################################
        # 重写分页查询，解决页码比查询数据可分页数据还大的问题
        page_size = self.get_page_size(request)
        # 数据最大的页码
        data_max_page = math.ceil(Paginator.count / page_size)

        if Paginator.count == 0: data_max_page = 1
        if data_max_page < int(page_number):
            page_number = data_max_page

        self.return_page = page_number
        ########################################

        return page_number
